function CacheUtil() {
}

function getCache(key) {
    return JSON.parse(window.sessionStorage.getItem(key));
}
function setCache (key, obj) {
    window.sessionStorage.setItem(key, JSON.stringify(obj))
}

CacheUtil.setCache = function (key, obj) {
    setCache(key, obj)
}

CacheUtil.getCache = function (key) {
    return getCache(key)
}

CacheUtil.exists = function (key) {
    return getCache(key) !== null
}

CacheUtil.cacheUser = function (obj) {
    // console.log("user", obj)
    setCache('user', obj)
    let authorities = [];
    obj.authorities.forEach((auth, index) => authorities.push(auth.authority))
    setCache("authorities", authorities)
}

CacheUtil.cacheUserInfo = function (obj) {
    setCache('userinfo', obj)
}

CacheUtil.getUserInfo = function (obj) {
    return getCache('userinfo')
}

CacheUtil.isUniversity = function (obj) {
    return hasRole('UNIVERSITY')
}
CacheUtil.isStudent = function (obj) {
    return hasRole('STUDENT')
}
CacheUtil.isCollege = function (obj) {
    return hasRole('COLLEGE')
}
CacheUtil.isTeacher = function (obj) {
    return hasRole('TEACHER')
}
CacheUtil.isAdmin = function (obj) {
    return hasRole('ADMIN')
}

function hasRole(role) {
    let roles = getCache('authorities')
    if (roles === null) return false;
    for (let i = 0; i < roles.length; i++) {
        if (roles[i].indexOf(role) !== -1) return true;
    }
    return false;
}

CacheUtil.getUserName = function () {
    // console.log(this.getUserInfo())
    if (this.getUserInfo() !== null) {
        return this.getUserInfo().name;
    } else {
        return "您好"
    }
}

CacheUtil.isLogin = function () {
    console.log("isLogin", this.getUser())
    return window.sessionStorage.getItem('user') !== null
}

CacheUtil.logout = function () {
    window.sessionStorage.clear();
}

function getRoles() {
    return getCache('authorities')
}

CacheUtil.getUser = function () {
    return getCache('user')
}

CacheUtil.clear = function () {
    window.sessionStorage.clear();
}

CacheUtil.setRestriction = function (data) {
    setCache('collegeInfoDto',data.data)
}

CacheUtil.getCollege = function () {
    return getCache('collegeInfoDto')
}


export default CacheUtil;
